"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { AuthGuard } from "@/components/auth-guard"
import { DashboardLayout } from "@/components/dashboard-layout"
import { LayeredCodeViewerV2 } from "@/components/layered-code-viewer-v2"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { ArrowLeft, Code2 } from "lucide-react"
import type { GeneratedLangGraphCodeV2 } from "@/lib/langgraph-generator-v2"

export default function CodeViewerPage() {
  const router = useRouter()
  const [generatedCode, setGeneratedCode] = useState<GeneratedLangGraphCodeV2 | null>(null)
  const [sourceType, setSourceType] = useState<string>("")
  const [sourceName, setSourceName] = useState<string>("")

  useEffect(() => {
    // 从 sessionStorage 读取代码数据（优先使用V2版本）
    const codeDataV2 = sessionStorage.getItem("langgraph_generated_code_v2")
    const type = sessionStorage.getItem("langgraph_source_type")
    const name = sessionStorage.getItem("langgraph_source_name")

    if (codeDataV2) {
      try {
        const parsed = JSON.parse(codeDataV2)
        setGeneratedCode(parsed)
        setSourceType(type || "")
        setSourceName(name || "")
      } catch (error) {
        console.error("Failed to parse code data:", error)
      }
    }
  }, [])

  const handleBack = () => {
    // 清理 sessionStorage
    sessionStorage.removeItem("langgraph_generated_code_v2")
    sessionStorage.removeItem("langgraph_generated_code")
    sessionStorage.removeItem("langgraph_source_type")
    sessionStorage.removeItem("langgraph_source_name")
    router.back()
  }

  if (!generatedCode) {
    return (
      <AuthGuard>
        <DashboardLayout>
          <div className="flex flex-col items-center justify-center h-[calc(100vh-8rem)] gap-4">
            <Code2 className="h-16 w-16 text-muted-foreground" />
            <div className="text-center space-y-2">
              <h2 className="text-2xl font-semibold">暂无代码数据</h2>
              <p className="text-muted-foreground">请从工作流或 Agent 编辑器生成代码</p>
            </div>
            <Button onClick={() => router.push("/dashboard/workflows")}>返回工作流列表</Button>
          </div>
        </DashboardLayout>
      </AuthGuard>
    )
  }

  return (
    <AuthGuard>
      <DashboardLayout>
        <div className="flex flex-col h-[calc(100vh-8rem)] gap-4">
          {/* 顶部导航栏 */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Button variant="ghost" size="sm" onClick={handleBack}>
                <ArrowLeft className="mr-2 h-4 w-4" />
                返回
              </Button>
              <div className="flex items-center gap-2">
                <Badge variant="outline" className="gap-1">
                  <Code2 className="h-3 w-3" />
                  {sourceType === "workflow" ? "工作流" : "Agent"}
                </Badge>
                <h1 className="text-xl font-semibold">{sourceName}</h1>
              </div>
            </div>
            <Badge variant="secondary">LangGraph 分层架构代码</Badge>
          </div>

          {/* 代码查看器 - 全屏展示 */}
          <div className="flex-1 min-h-0">
            <LayeredCodeViewerV2 generatedCode={generatedCode} />
          </div>
        </div>
      </DashboardLayout>
    </AuthGuard>
  )
}
